package faceb.server.interceptor;

import java.util.HashSet;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import faceb.server.model.User;
import faceb.server.util.ServerFinal;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	private Set<String> filterUrls = new HashSet<String>();
	private Set<String> ResourcesUrls = new HashSet<String>();

	public LoginInterceptor() {
		super();
		filterUrls.add("/faceb-cupt/deallogin");
		filterUrls.add("/faceb-cupt/register");
		filterUrls.add("/faceb-cupt/dealregister");
		filterUrls.add("/faceb-cupt/tpl/login");
		
		ResourcesUrls.add("/faceb-cupt/util/");
		ResourcesUrls.add("/faceb-cupt/js/");
		ResourcesUrls.add("/faceb-cupt/css/");
		ResourcesUrls.add("/faceb-cupt/img/");
		ResourcesUrls.add("/faceb-cupt/lib/");
		ResourcesUrls.add("/faceb-cupt/scss/");
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// 设置请求和相应的字符编码
		request.setCharacterEncoding(ServerFinal.CHAR_ENCODING);
		response.setCharacterEncoding(ServerFinal.CHAR_ENCODING);

		System.out.println("preHandle");
		String requesturl = request.getRequestURI();
		System.out.println("requestUrl:" + requesturl);
		
		
		boolean isstaticRes = false;
		/****静态资源 img,js,css处理****/
		for (String url:ResourcesUrls) {
			if(requesturl.startsWith(url)){
				isstaticRes=true;
				break;
			}
		}
		if(isstaticRes)
			return true;
		
		
		
		
		// 如果在指定的url集合里面，则不拦截，因为要在spring MVC
		// 3.2.0版本之后才有拦截器不拦截的url配置，所以这里自己手动处理啦。
		if (filterUrls.contains(requesturl)) {
			return true;
		}
		
		
		
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		System.out.println("user:" + user);
		if (user == null) {
			request.getRequestDispatcher("/tpl/login").forward(
					request, response);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("postHandle");
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("after intereceptor");

	}
}
